package com.xwaf.platform.system.auth.task;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.xwaf.platform.system.auth.task.data.ImportData;
import com.xwaf.platform.system.auth.task.data.ImportData.ImportIingType;
import com.xwaf.platform.system.auth.task.data.Pool;
import com.xwaf.platform.system.auth.task.resolve.OrderResolve;

/**
 * 
 * <p>
 * 导入处理分发
 * <p>
 * 
 * @author 李聪 <br>
 * @email xwaf_love@yeah.net <br>
 * @since JDK 1.8<br>
 * @date 2020年1月4日 下午1:30:55 <br>
 * @see 无<br>
 *      Copyright (c) 2020, xwaf_love@yeah.net All Rights Reserved.<br>
 */
@Component("distributionTask")
public class DistributionTask {

	private static final Logger logger = LoggerFactory.getLogger(DistributionTask.class);

	/**
	 * 1分钟执行一次
	 */
	@Scheduled(cron = "0 0/1 * * * ?")
	public void run() {
		// logger.info("start distribution import");
		for (String companyId : Pool.keySet()) {
			List<ImportData> importDatas = Pool.get(companyId);
			boolean isUploadFree = true;
			for (ImportData data : importDatas) {
				if (data.getImportingType() == ImportIingType.IMPORTING) {
					isUploadFree = false;
					break;
				}
			}
			if (isUploadFree) {
				List<ImportData> removeDatas = new ArrayList<>();
				for (ImportData data : importDatas) {
					if (data.getImportingType() == ImportIingType.FINISH) {
						removeDatas.add(data);
					}
				}
				for (ImportData removeObj : removeDatas) {
					importDatas.remove(removeObj);
				}
				if (importDatas != null && importDatas.size() > 0) {
					ImportData importData = importDatas.get(0);
					importData.setImportingType(ImportIingType.IMPORTING);
					String key = importData.getStrType();
					switch (key) {
					case "order":
						importData.getImportTaskExecutor()
								.execute(new OrderResolve(importData.getId(), importData.getFilePath(),
										importData.getFileName(), importData.getSaveErrorUrl(),
										importData.getSaveErrorFile(), importData.getUser(), importData.getCtx(),
										importData.getLocal()));
						break;
					default:
						break;
					}
				}
			}
		}
		// logger.info("end distribution import");
	}
}
